#!/usr/bin/perl
#
# Validate a machine entry
# Note: This is also responsible for making single entries
#       out of the multi-field entries.
#
use strict;

use CGI;
# Counter specific
use Counter;
use CounterCGI;
use ErrorForm;
use POSIX;
#use IsEmail qw(isemail $notemailbecause);

use vars qw($prefix);
use vars qw($machine $machines $mach $user $users $userno %knownfield);
use vars qw($clean %used $oldrec $n $entry $value $validator);
use vars qw($warnuserentry $key $oldstuff $operation $newowner);
use vars qw($newkey $delete);

warn "INC is ", join(" ", @INC);
$prefix = "db";

# Parse the entry
$entry = new CGI;

$users = Counter::open(O_RDONLY|O_CREAT);
$machines = Counter::openfile("machines");
$validator = new Validate::Machines;

# Fields that this script recognizes from an old record
# Unknown fields raise a debug message
%knownfield = (
"method", 1,
"recdate", 1,
"f_ctime", 1,
"f_mtime", 1,
"ident", 1,
"nocookie", 1,
	       );

# Check whether key is correct
$user = CounterCGI::requirelogin($users, $entry);
$userno = $user->key();
$operation = "create";

# Forwarding a function name...
#sub _ { gettext(@_)}

# For updated machines: Try to find the old record
if ($entry->param("machine")) {
    $mach = grab($entry, "machine");
    # Check if this was a Delete command
    if (grab($entry, "delete")) {
	# Do delete processing
	print STDERR "machine-validate: delete $mach\n";
	$operation = "delete";
	$delete = 1;
    } else {
	print STDERR "machine-validate: update $mach\n";
	grab($entry, "enter"); # mark this field used
	$operation = "update";
    }
    $oldrec = $machines->get($mach);
    if (!$oldrec) {
#	errorForm("Machine $mach not found in database");
	CounterCGI::returnwithmessage($entry, CounterCGI::__("Machine $mach not found in database"));
    }
    if ($oldrec->{owner} ne $userno) {
#	errorForm("This machine is not owned by $userno");
	CounterCGI::returnwithmessage($entry, CounterCGI::__("This machine is not owned by $userno"));
    }
    $knownfield{owner} = 1;
}

if ($operation eq "delete") {
    dodelete();
    exit(0);
}
$newkey = grab($entry, "newkey");
if ($newkey) {
    if ($newkey =~ /^(\d+)-\d+$/) {
	$newowner = $users->get($1);
	if ($newowner->{key} ne $newkey) {
	    print STDERR "Attempted to give to $newkey, he has ",
	    $newowner->{key}, "\n";
	    #errorForm("bogus new owner");
            CounterCGI::returnwithmessage($entry, CounterCGI::__("bogus new owner"));
	}
    } else {
	    #errorForm("syntactically bogus new owner");
	    CounterCGI::returnwithmessage($entry, CounterCGI::__("syntactically bogus new owner"));
    }
}

# ----------- GENERATE REPLY ----------------
# Note: below this line, we can't use errorForm to bail out...
# syntax is supposed to be reasonably OK here.
   
print <<EoF;
Content-type: text/html; charset="utf-8"

<html>
EoF

CounterCGI::pagehead(__("Machine registration review"));
print "<body bgcolor=\"white\">\n";
CounterCGI::pagetop($entry);

print "<h1><img src=\"/gifs/Logo-small.png\">";
print __("Machine registration - review"), "</h1>\n";
print __("The table below shows what you entered, and, if relevant, what the counter will summarize what you entered as.");
print "\n<p>\n";
print __("If you like what you see, press \"I accept\" below. If you don't, use the \"back\" button in your browser to go back and modify it.");
print "\n<p>\n";
print __("Note that this is the internal counter representation; it's been chosen for utility, not beauty!");
print "\n<p>\n";

print __("You are Linux Counter user"), " #$userno<br>\n";

if ($oldrec) {
    print __("This is machine"), " #$mach<br>\n";
    $oldstuff = "<th>" . __("Old value") . "</th>";
}
print "<FORM METHOD=POST action=\"/perl/machine-counter.pl\">\n";
print "<input type=hidden name=operation value=\"$operation\">\n";
if ($oldrec) {
    print "<input type=hidden name=machine value=\"$mach\">\n";
}
# get newkey
if ($oldrec && grab($entry, "newkey")) {
    print "<input type=hidden name=newkey value=\"",
    $entry->param("newkey"), "\">\n";
    print __("You are giving this machine to user"), " #", $newowner->key,
	", ", $newowner->{email}, "<br>\n";
}


print "<table border>\n";
print "<tr><th>", __("Field"), "</th>", $oldstuff, "<th>", __("You entered"), "</th><th>", __("Sums in statistics as"), "</th></tr>";
# Include the key information
print "<input type=hidden name=key value=\"",
    $key, "\">\n";
$used{key} = 1;
if ($entry->param("nocookie")) {
    print '<input type="hidden" name="nocookie" value="'
	. $entry->param("nocookie") . '">';
    $used{nocookie} = 1;
}

# Now try to make the form into a machine entry
for my $field ($machines->fields) {
    # Calculate value and cleanliness
    $knownfield{$field} = 1;
    $value = "";
    if ($field eq "cpu") {
	if ($entry->param("cpu")) {	
	    # Simple version - this is used by "update"
	    $value = grab($entry, "cpu");
	} else {
	    # Complex version - used in initial entry
	    my $count = grab($entry, "cpu-count");
	    my $type = grab($entry, "cpu-type"); # Contains maker and type of CPU !!
	    my $speed = grab($entry, "cpu-speed");
	    my $comment = grab($entry, "cpu-comment");

	    $value = "$type/$speed";
	    if ($count && $count > 1) {
		$value = "${count} " . $value;
	    }
	    if ($comment) {
		$value .= " ($comment)";
	    }
	}
    } elsif ($field eq "source") {
	if ($entry->param("source")) {
	    $value = grab($entry, "source");
	} else {
	    if ($entry->param("source-main")) {
		$value = $entry->param("source-main");
		if ($entry->param("source-detail")) {
		    $value .= "/";
		    $value .= $entry->param("source-detail");
		}
	    }
	    $used{"source-main"} = 1;
	    $used{"source-detail"} = 1;
	}
    } elsif ($field eq "distribution") {
	$value = grab($entry, "distribution");
	if (grab($entry, "distribution-version")) {
	    $value .= " ";
	    $value .= grab($entry, "distribution-version");
	}
    } elsif ($field eq "disk") {
	$value = grab($entry, "disk");
	my $unit = grab($entry, "unit");
	# warn "DISK: $value, $unit" ;
	if ($unit eq "GB") {
            #  warn "DISK: GB";
	    $value = int($value*1024);
	} elsif ($unit eq "TB") {
            # warn "DISK: TB";
	    $value = int($value*1048576);
	}
	# warn "DISK: $value, $unit" ;
    } else {
	$value = grab($entry, $field);
    }
    if (length($value) > 0) {
	$clean = $validator->cleanfield($field, $value);
	if ($clean eq $value) {
	    $clean = "";
	} elsif ($clean eq "") {
	    $clean = "<b>" . __("Will be ignored") . "</b>";
	}
    } else {
	$clean = __("Not given");
    }
    print "<input type=hidden name=$field value=\"$value\">\n";
    print "<tr><td>", $field?$field:"&nbsp;", "</td>";
    if ($oldrec) {
	print "<td>", $oldrec->{$field}, "</td>";
    }
    print "<td>$value</td><td>$clean</td></tr>\n";
}
print "</table>\n";
for my $field ($entry->param) {
    if (!$used{$field}) {
	print "DEBUG: Unused field: $field = ",
	$entry->param($field), "<br>\n";
    }
}
if ($oldrec) {
    for $n (keys(%$oldrec)) {
	if ($n !~ /^\*/ && !$knownfield{$n}) {
	    print "DEBUG: Lost old field: ";
	    print "$n: $oldrec->{$n}<br>\n";
	}
    }
}

print "\n<p>\n";
print "<inPUT TYPE=\"submit\" VALUE=\"", __("I accept"), "!\">";
print "</form>\n";
CounterCGI::pagebottom();
print "\n</body>\n</html>";

sub grab {
    my ($entry, $name) = @_;
    $used{$name} = 1;
    my @values = $entry->param($name);
    # delete leading blank entries
    shift @values while $#values > -1
	&& (!defined($values[0]) || $values[0] eq "");
    my $value = join(", ", @values);
    $value =~ s/(, )+$//; # delete trailing blank entry, if any
    return $value;
}

	
#---------------- DELETE PROCESSING ------------------------
# a bit ugly....
#

sub dodelete {
    #$machines->close();
    #$users->close();
    $machines = Counter::openfile("machines", O_RDWR|O_CREAT);
    $users = Counter::openfile("users", O_RDWR|O_CREAT);
    $machine = $machines->get($mach);
    errorForm("Get machine error") if !$machine;
    $user = $users->get($userno);
    errorForm("Get user error") if !$user;
    $user->{machines} =~ s/ ?$mach//;
    $machine->delete();
    $user->store();
    print <<EoF;
content-type: text/html; charset="utf-8"

<html>
<head>
EoF
print "<title>", __("Machine"), " $mach ", __("deleted"), "</title>\n";
print "</head>\n<body>\n";
print "<h1><img src=\"/gifs/Logo-small.png\">";
print __("Machine"), " $mach ", __("has been deleted"), "</h1>\n";
CounterCGI::pagebottom();
print "\n</body>\n</html>";

}

